﻿#-*- coding: utf-8 -*-

from db_helper import CursorReaderBase, ConnectionBase
import MySQLdb as mysql

class CursorReader(CursorReaderBase):
	''''''
	def __init__(self, cursor, columns = []):
		self.cur = cursor
		self.row = None
		self.columns = columns
	
	def get_column(self, index):
		if self.columns is not None:
			if len(self.columns):
				return self.columns[index]
		return '%s' % index

	def read(self):
		row = self.cur.fetchone()
		if row is not None:
			self.row = {}
			# print row
			for i in range(0, len(row)):
				self.row[self.get_column(i)] = row[i]
			return True
		self.row = None
		return False

class Connection(ConnectionBase):
	
	@staticmethod
	def create(*args, **kargs):
		kargs['auto_connect'] = False
		new_conn = Connection(*args, **kargs)
		try_create_db = False
		try:
			new_conn.connect()
		except mysql.OperationalError, e:
			code, errmsg = e.args
			# code 1049 represents 'unknown database'.
			# code 1046 represents 'no database selected'.
			if code == 1049:
				try_create_db = True
		if try_create_db:
			pass
		return new_conn
	
	def __init__(self, server='localhost', user='root',
		pwd='', port=None, dbname='', auto_connect=True):
		self.config = {
			'server': server,
			'port': port if port else 3306, 
			'user': user, 
			'pwd': pwd,
			'dbname': dbname
		}
		self.conn = None
		self.cur = None
		self.lastsql = ''
		if auto_connect:
			self.connect()
	
	def create_database(self):
		pass
	
	@property
	def lastrowid(self):
		return self.cur.lastrowid
	
	def execute(self, *args):
		sql = self.build_sql(*args)
		if len(sql)>0:
			self.connect()
			self.lastsql = sql
			self.cur.execute(sql)
			self.conn.commit()
	
	def execute_reader(self, sql):
		self.connect()
		self.lastsql = sql
		self.cur.execute(sql)
		col_desc = self.cur.description
		cols = [c[0] for c in col_desc]
		reader = CursorReader(self.cur, columns = cols)
		return reader
	
	def get_tables(self):
		sql = 'select distinct(table_name) from information_schema.columns where table_schema=%s'
		results = self.read(sql, self.config['dbname'])
		return [row['table_name'] for row in results]
	
	def connect(self):
		if self.conn is None:
			self.conn = mysql.connect(host=self.config['server'], 
				user=self.config['user'], passwd=self.config['pwd'],
				db=self.config['dbname'], charset='utf8')
			self.cur = self.conn.cursor()
	
	def close(self):
		if self.cur:
			self.cur.close()
			self.cur = None
		if self.conn:
			self.conn.close()
			self.conn = None
